const express = require('express');
const path = require('path');
const fs = require('fs');

const app = express();
const PORT = process.env.PORT || 3000;

// 检查dist目录是否存在
const distPath = path.join(__dirname, 'dist');
if (!fs.existsSync(distPath)) {
  console.error('❌ dist目录不存在，请先运行 npm run build');
  process.exit(1);
}

// CORS中间件 - 允许前端访问API
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
  
  // 处理预检请求
  if (req.method === 'OPTIONS') {
    res.sendStatus(200);
  } else {
    next();
  }
});

// 解析POST请求的表单数据
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

// 静态文件服务
app.use(express.static(distPath));

// 处理POST请求（用于form_post回调）
app.post('/auth/ms-365-auth/callback', (req, res) => {
  console.log('📥 收到POST回调请求');
  console.log('📥 请求头:', req.headers);
  console.log('📥 请求体:', req.body);
  console.log('📥 表单数据:');
  console.log('- code:', req.body.code);
  console.log('- state:', req.body.state);
  console.log('- session_state:', req.body.session_state);
  console.log('- error:', req.body.error);
  console.log('- error_description:', req.body.error_description);
  
  // 将回调参数作为查询字符串传递给前端
  const params = new URLSearchParams();
  if (req.body.code) params.append('code', req.body.code);
  if (req.body.state) params.append('state', req.body.state);
  if (req.body.session_state) params.append('session_state', req.body.session_state);
  if (req.body.error) params.append('error', req.body.error);
  if (req.body.error_description) params.append('error_description', req.body.error_description);
  
  const queryString = params.toString();
  const redirectUrl = queryString ? `/auth/ms-365-auth/callback?${queryString}` : '/auth/ms-365-auth/callback';
  
  console.log('🔄 重定向到:', redirectUrl);
  
  // 重定向到GET请求，让前端处理回调
  res.redirect(redirectUrl);
});

// 处理授权码交换的API端点
app.post('/api/auth/exchange-code', async (req, res) => {
  try {
    console.log('🔄 收到授权码交换请求');
    console.log('📋 请求体:', req.body);
    
    const { code, scopes, redirectUri } = req.body;
    
    if (!code) {
      return res.status(400).json({ error: '缺少授权码' });
    }
    
    // Azure AD配置
    const clientId = '6c1f2122-b1e9-45a1-af19-ba68978278a3';
    const tenantId = 'afebf5f7-d49a-419a-8d2c-5d08baabdee1';
    const clientSecret = 'G8S8Q~y3SaEDcbBh44nTgUVW~czREsJDaEwwfckX';
    
    console.log('✅ 使用配置的客户端密钥进行令牌交换');
    
    // 构造令牌交换请求
    const tokenUrl = `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`;
    const tokenData = new URLSearchParams({
      client_id: clientId,
      client_secret: clientSecret,
      code: code,
      redirect_uri: redirectUri,
      grant_type: 'authorization_code',
      scope: scopes.join(' ')
    });
    
    console.log('🔧 令牌交换请求URL:', tokenUrl);
    console.log('🔧 令牌交换参数:', {
      client_id: clientId,
      code: code.substring(0, 20) + '...',
      redirect_uri: redirectUri,
      scope: scopes.join(' ')
    });
    
    // 发送令牌交换请求
    const response = await fetch(tokenUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: tokenData.toString()
    });
    
    const responseText = await response.text();
    console.log('📋 Azure AD响应状态:', response.status);
    console.log('📋 Azure AD响应内容:', responseText);
    
    if (!response.ok) {
      console.error('❌ 令牌交换失败:', response.status, responseText);
      return res.status(response.status).json({ 
        error: '令牌交换失败', 
        details: responseText 
      });
    }
    
    const tokenResponse = JSON.parse(responseText);
    console.log('✅ 令牌交换成功');
    
    // 返回令牌信息
    res.json({
      access_token: tokenResponse.access_token,
      token_type: tokenResponse.token_type,
      expires_in: tokenResponse.expires_in,
      refresh_token: tokenResponse.refresh_token,
      scope: tokenResponse.scope
    });
    
  } catch (error) {
    console.error('❌ 授权码交换处理失败:', error);
    res.status(500).json({ 
      error: '服务器内部错误', 
      details: error.message 
    });
  }
});

// SPA路由处理 - 所有未匹配的路由都返回index.html
app.get('*', (req, res) => {
  console.log(`🔄 SPA路由: ${req.method} ${req.url}`);
  res.sendFile(path.join(distPath, 'index.html'));
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error('❌ 服务器错误:', err);
  res.status(500).send('服务器内部错误');
});

app.listen(PORT, () => {
  console.log(`🚀 服务器运行在 http://localhost:${PORT}`);
  console.log(`📁 静态文件目录: ${distPath}`);
  console.log(`🔄 SPA路由已启用，所有路由都会重定向到index.html`);
  console.log(`📥 POST回调路由: /auth/ms-365-auth/callback`);
}); 